package thread;

/**
 * @author lwmzzz
 * @version 1.0
 * @date 2021/1/26 23:29
 * @description 线程通信Demo
 */
public class ThreadInteractDemo {
    public static void main(String[] args) {
        Number number = new Number();
        Number1 number1 = new Number1();
//        new Thread(number).start();
//        new Thread(number).start();
//        new Thread(number).start();
//        new Thread(number).start();
//
        new Thread(number1).start();
        new Thread(number1).start();
        new Thread(number1).start();
    }
}

class Number implements Runnable {
    private int i = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                this.notify();
                if (i <= 100) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " " + i);
                    i++;
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}

class Number1 implements Runnable {
    private int i = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (i <= 100) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " " + i);
                    i++;

                } else {
                    break;
                }
            }
        }
    }
}
